package com.example.musicdemo1

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import com.bumptech.glide.Glide
import com.example.musicdemo1.service.MusicPlayer
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import com.example.musicdemo1.api.PlaylistApi
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {
    private  var baseUrl = "http://121.37.40.55:3000/"

    private lateinit var miniPlayer: View
    private lateinit var miniCoverImage: ImageView
    private lateinit var miniTitleText: TextView
    private lateinit var miniArtistText: TextView
    private lateinit var miniPlayPauseButton: ImageButton
    private lateinit var miniPlaylistButton: ImageButton
    private lateinit var miniNextButton: ImageButton
    private lateinit var minpreviouButton: ImageButton

    // 修改API初始化方式
    private val api: PlaylistApi by lazy {
        val logging = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        
        val client = OkHttpClient.Builder()
            .addInterceptor(logging)
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build()

        Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(PlaylistApi::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        setupNavigation()
        setupMiniPlayer()
        observePlaybackState()
        loadInitialPlaylist()
    }

    private fun setupNavigation() {
        val navHostFragment = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        
        val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
        
        // 添加标签页
        tabLayout.addTab(tabLayout.newTab().setText("推荐"))
        tabLayout.addTab(tabLayout.newTab().setText("播放器"))
        tabLayout.addTab(tabLayout.newTab().setText("播放列表"))
        
        // 设置标签页选择监听
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                when (tab.position) {
                    0 -> navController.navigate(R.id.navigation_recommend)
                    1 -> navController.navigate(R.id.navigation_player)
                    2 -> navController.navigate(R.id.navigation_playlist)
                }
            }
            
            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
    }

    private fun setupMiniPlayer() {
        miniPlayer = findViewById(R.id.miniPlayer)
        miniCoverImage = findViewById(R.id.miniCoverImage)
        miniTitleText = findViewById(R.id.miniTitleText)
        miniArtistText = findViewById(R.id.miniArtistText)
        miniPlayPauseButton = findViewById(R.id.miniPlayPauseButton)
        miniPlaylistButton = findViewById(R.id.miniPlaylistButton)
        miniNextButton = findViewById(R.id.miniNextButton)
        minpreviouButton = findViewById(R.id.minpreviouButton)

        miniPlayer.setOnClickListener {
            findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_player)
        }

        miniPlayPauseButton.setOnClickListener {
            if (MusicPlayer.isPlaying.value) {
                MusicPlayer.pause()
            } else {
                MusicPlayer.resume()
            }
        }

        miniPlaylistButton.setOnClickListener {
            findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_playlist)
        }

        miniNextButton.setOnClickListener {
            MusicPlayer.playNext()
        }
        minpreviouButton.setOnClickListener{
            MusicPlayer.playPrevious()
        }
    }

    private fun observePlaybackState() {
        lifecycleScope.launch {
            MusicPlayer.currentMusic.collectLatest { music ->
                music?.let {
                    miniTitleText.text = it.title
                    miniArtistText.text = it.singer
                    Glide.with(this@MainActivity)
                        .load(it.coverImgUrl)
                        .into(miniCoverImage)
                }
            }
        }

        lifecycleScope.launch {
            MusicPlayer.isPlaying.collectLatest { isPlaying ->
                miniPlayPauseButton.setImageResource(
                    if (isPlaying) R.drawable.ic_custom_pause
                    else R.drawable.ic_custom_play
                )
            }
        }
    }

    private fun loadInitialPlaylist() {
        lifecycleScope.launch {
            try {
                val playlist = api.getPlaylist()
                MusicPlayer.setPlaylist(playlist)
            } catch (e: Exception) {
                Log.e("MainActivity", "加载播放列表失败", e)
            }
        }
    }
}